#!/bin/bash
#
# startup.sh -- lab specific startup script,
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#

TOP_DIR=$(cd $(dirname $0) && pwd)/

[ ! -d /proc ] && mount -t proc none /proc

# nfsd.ko must be inserted to enable nfs kernel server
grep -qi intel /proc/cpuinfo
if [ $? -eq 0 ]; then
  kvm_dri=kvm-intel
else
  kvm_dri=kvm-amd
fi

modules="loop minix nfsd 9pnet_virtio kvm $kvm_dri"

if [ $? -eq 0 ]; then
  for m in $modules
  do
    modprobe -d /m -n $m >/dev/null 2>&1
    [ $? -ne 0 ] && continue

    lsmod | grep -q $m
    [ $? -ne 0 ] && modprobe -d/m $m >/dev/null 2>&1

    # tell user enable cpu virtualization in bios if not disabled
    if [ $? -ne 0 ]; then
      if [ "$m" = "kvm-intel" -o "$m" = "kvm-amd" ]; then
        echo "LOG: Please turn on cpu virtualization in bios if want use kvm speedup"
      fi
    fi
  done
fi

# For qemu-mips64el
[ ! -f /proc/sys/fs/binfmt_misc/regisiter ] && mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
if [ ! -f /proc/sys/fs/binfmt_misc/mips64el -a -f /proc/sys/fs/binfmt_misc/register ]; then
  sh -c "echo ':mips64el:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x08\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-mips64el:' > /proc/sys/fs/binfmt_misc/register"
fi

# Configure for core-dump
# echo "/tmp/cores/core.%e.%p" > /proc/sys/kernel/core_pattern
echo core > /proc/sys/kernel/core_pattern

# Enable network bridge support

$TOP_DIR/enable_net_bridge.sh

## Start Net servers
$TOP_DIR/restart-net-servers.sh

## Install aarch64-linux-gnu-gcc alternatives
[ -f /usr/bin/aarch64-linux-gnu-gcc-4.8 ] && \
  update-alternatives --install /usr/bin/aarch64-linux-gnu-gcc aarch64-linux-gnu-gcc /usr/bin/aarch64-linux-gnu-gcc-4.8 45
[ -f /usr/local/bin/aarch64-linux-gnu-gcc-4.9.3 ] && \
  ln -sf /usr/local/bin/aarch64-linux-gnu-gcc-4.9.3 /usr/bin/aarch64-linux-gnu-gcc-4.9.3 && \
  update-alternatives --install /usr/bin/aarch64-linux-gnu-gcc aarch64-linux-gnu-gcc /usr/bin/aarch64-linux-gnu-gcc-4.9.3 46
